
source('utils.R')
source('read_dataset.R')

s1d = df20[,.(biden = sum(d_ind)/.N, trump20 = sum(r_ind)/.N, N20 = .N), .(nat_dec)][order(nat_dec)]
s2d = df16[,.(clinton = sum(d_ind)/.N, trump16 = sum(r_ind)/.N, N16 = .N), .(nat_dec)][order(nat_dec)]
s3d = df12[,.(romney = sum(r_ind)/.N, obama12 = sum(d_ind)/.N, N12 = .N), .(nat_dec)][order(nat_dec)]

s1 = df20[,.(biden = sum(d_ind)/.N, trump20 = sum(r_ind)/.N, N20 = .N), .(nat_quant)][order(nat_quant)][as.numeric(nat_quant)>=10]
s2 = df16[,.(clinton = sum(d_ind)/.N, trump16 = sum(r_ind)/.N, N16 = .N), .(nat_quant)][order(nat_quant)][as.numeric(nat_quant)>=10]
s3 = df12[,.(romney = sum(r_ind)/.N, obama12 = sum(d_ind)/.N, N12 = .N), .(nat_quant)][order(nat_quant)][as.numeric(nat_quant)>=10]

out_summ = rbindlist(list(cbind(s1d[,1:4], s2d[,2:4], s3d[,2:4]),cbind(s1[,1:4], s2[,2:4], s3[,2:4])),use.names=T,fill=T)
out_summ[,nat_quant := fifelse(is.na(nat_dec)|as.numeric(nat_dec)>1,as.character(nat_quant),as.character(nat_dec)) |> as.factor()]
out_summ[,2:10] = out_summ[, lapply(.SD, as.numeric), .SDcols = c(2:10)]
out_summ = melt(out_summ[,2:11],id.vars = 10)
out_summ[,type:='Raw Rates']
out_summ[,nat_quant:=as.character(nat_quant)]
out_summ[is.na(nat_quant),nat_quant:='0.85'] # just to order them properly

s1d = df20[,.(biden = sum(d_val)/.N, trump20 = sum(r_val)/.N, N20 = .N), .(nat_dec)][order(nat_dec)]
s2d = df16[,.(clinton = sum(d_val)/.N, trump16 = sum(r_val)/.N, N16 = .N), .(nat_dec)][order(nat_dec)]
s3d = df12[,.(romney = sum(r_val)/.N, obama12 = sum(d_val)/.N, N12 = .N), .(nat_dec)][order(nat_dec)]

s1 = df20[,.(biden = sum(d_val)/.N, trump20 = sum(r_val)/.N, N20 = .N), .(nat_quant)][order(nat_quant)][as.numeric(nat_quant)>=10]
s2 = df16[,.(clinton = sum(d_val)/.N, trump16 = sum(r_val)/.N, N16 = .N), .(nat_quant)][order(nat_quant)][as.numeric(nat_quant)>=10]
s3 = df12[,.(romney = sum(r_val)/.N, obama12 = sum(d_val)/.N, N12 = .N), .(nat_quant)][order(nat_quant)][as.numeric(nat_quant)>=10]


out_summ2 = rbindlist(list(cbind(s1d[,1:4], s2d[,2:4], s3d[,2:4]),cbind(s1[,1:4], s2[,2:4], s3[,2:4])),use.names=T,fill=T)
out_summ2[,nat_quant := fifelse(is.na(nat_dec)|as.numeric(nat_dec)>1,as.character(nat_quant),as.character(nat_dec)) |> as.factor()]
out_summ2[,2:10] = out_summ2[, lapply(.SD, as.numeric), .SDcols = c(2:10)]
out_summ2 = melt(out_summ2[,2:11],id.vars = 10)
out_summ2[, type:='Raw Per-Capita Contributions']

save(out_summ, out_summ2, file = 'summary_data/figA6.rda')
